<template>
  <div class="admin-layout">
    <!-- 侧边栏 -->
    <el-aside width="220px" class="admin-aside">
      <div class="logo">
        <h3>{{ systemTitle }}</h3>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="admin-menu"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <el-menu-item index="/admin/business-stats" v-if="hasMenuPermission(1)">
          <i class="el-icon-data-line"></i>
          <span slot="title">业务统计</span>
        </el-menu-item>
        <el-menu-item index="/admin/project-overview" v-if="hasMenuPermission(2)">
          <i class="el-icon-document"></i>
          <span slot="title">项目总览</span>
        </el-menu-item>
        <el-menu-item index="/admin/labeler-management" v-if="hasMenuPermission(3)">
          <i class="el-icon-user"></i>
          <span slot="title">标注员管理</span>
        </el-menu-item>
        <el-menu-item index="/admin/labeler-daily-output" v-if="hasMenuPermission(4)">
          <i class="el-icon-date"></i>
          <span slot="title">标注员产值记录</span>
        </el-menu-item>
        <el-menu-item index="/admin/labeler-box-count" v-if="hasMenuPermission(5)">
          <i class="el-icon-s-grid"></i>
          <span slot="title">标注员拉框数</span>
        </el-menu-item>
        <el-menu-item index="/admin/qc-statistics" v-if="hasMenuPermission(6)">
          <i class="el-icon-pie-chart"></i>
          <span slot="title">质检统计</span>
        </el-menu-item>
        <el-menu-item index="/admin/excellent-labeler" v-if="hasMenuPermission(7)">
          <i class="el-icon-medal"></i>
          <span slot="title">优秀标注员</span>
        </el-menu-item>
        <el-menu-item index="/admin/excellent-manager" v-if="hasMenuPermission(8)">
          <i class="el-icon-user"></i>
          <span slot="title">优秀项目经理</span>
        </el-menu-item>
        <el-menu-item index="/admin/data-project" v-if="hasMenuPermission(9)">
          <i class="el-icon-document-copy"></i>
          <span slot="title">数据项目看板</span>
        </el-menu-item>
        <el-menu-item index="/admin/screen-config" v-if="hasMenuPermission(10)">
          <i class="el-icon-setting"></i>
          <span slot="title">大屏配置</span>
        </el-menu-item>
        <el-menu-item index="/admin/menu-permission" v-if="hasMenuPermission(12)">
          <i class="el-icon-setting"></i>
          <span slot="title">菜单权限分配</span>
        </el-menu-item>
        <!-- 供应商采集管理菜单项 -->
        <el-menu-item index="/admin/supplier-collection" v-if="hasMenuPermission(11)">
          <i class="el-icon-office-building"></i>
          <span slot="title">供应商采集管理</span>
        </el-menu-item>

      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container class="admin-container">
      <!-- 顶部导航 -->
      <el-header class="admin-header">
        <div class="header-left">
          <span>{{ currentPageTitle }}</span>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <i class="el-icon-user-solid"></i>
              {{ userName }} ({{ userRole }})
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="bigscreen">返回大屏</el-dropdown-item>
              <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区域 -->
      <el-main class="admin-main">
        <router-view></router-view>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import 'element-ui/lib/theme-chalk/index.css';
import { logout } from '@/utils/auth';
import { RolePermissionUtil } from '@/utils/rolePermission';
import axios from 'axios';

export default {
  name: 'AdminLayout',
  data() {
    return {
      userName: 'Admin',
      userRole: '',
      userMenus: null  // 初始化为null而不是空数组
    };
  },
  computed: {
    activeMenu() {
      return this.$route.path;
    },
    // 动态系统标题
    systemTitle() {
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      return user.companyName ? user.companyName + '管理系统' : '数据标注大屏后台管理系统';
    },
    currentPageTitle() {
      // 获取当前用户信息
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      // 构建系统标题
      const systemTitle = (user.companyName ? user.companyName + '管理系统' : '数据标注大屏后台管理系统');
      
      const titles = {
        '/admin/business-stats': '业务统计管理',
        '/admin/project-overview': '项目总览管理',
        '/admin/labeler-management': '标注员管理',
        '/admin/labeler-daily-output': '标注员产值记录',
        '/admin/labeler-box-count': '标注员拉框数实时看板',
        '/admin/qc-statistics': '质检质检量统计图',
        '/admin/excellent-labeler': '优秀标注员荣誉榜',
        '/admin/excellent-manager': '优秀项目经理（TOP8）',
        '/admin/data-project': '数据项目实时看板',
        '/admin/screen-config': '大屏配置管理',
        '/admin/supplier-collection': '供应商采集管理',
        '/admin/menu-permission': '菜单权限分配'
      };
      
      // 如果是首页或管理系统根路径，显示系统标题
      if (this.$route.path === '/admin' || this.$route.path === '/admin/') {
        return systemTitle;
      }
      
      // 否则显示具体页面标题
      const pageTitle = titles[this.$route.path] || '管理系统';
      return systemTitle + ' - ' + pageTitle;
    },
    // 角色权限计算属性
    isAdmin() {
      return RolePermissionUtil.isAdmin();
    },
    isManager() {
      return RolePermissionUtil.isManager();
    },
    isLabeler() {
      return RolePermissionUtil.isLabeler();
    },
    isQc() {
      return RolePermissionUtil.isQc();
    }
  },
  created() {
    // 检查登录状态
    const token = localStorage.getItem('access_token');
    if (!token) {
      this.$router.push('/admin/login');
    } else {
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      this.userName = user.username || 'Admin';
      
      // 获取用户角色
      this.userRole = RolePermissionUtil.getCurrentRole() || '未知';
      
      // 加载用户菜单权限
      this.loadUserMenus();
    }
    
    // 监听用户信息更新事件
    this.handleUserProfileUpdated = (event) => {
      const user = event.detail;
      this.userName = user.username || 'Admin';
      // 强制更新计算属性
      this.$forceUpdate();
    };
    
    // 监听系统标题更新事件
    this.handleSystemTitleUpdated = (event) => {
      // 触发重新计算systemTitle
      this.$forceUpdate();
    };
    
    window.addEventListener('userProfileUpdated', this.handleUserProfileUpdated);
    window.addEventListener('systemTitleUpdated', this.handleSystemTitleUpdated);
  },
  beforeDestroy() {
    // 移除事件监听器
    if (this.handleUserProfileUpdated) {
      window.removeEventListener('userProfileUpdated', this.handleUserProfileUpdated);
    }
    if (this.handleSystemTitleUpdated) {
      window.removeEventListener('systemTitleUpdated', this.handleSystemTitleUpdated);
    }
  },
  methods: {
    // 加载用户菜单权限
    loadUserMenus() {
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      console.log('当前用户信息:', user);
      
      // 检查是否有有效的用户ID
      if (!user || !user.id) {
        console.log('未找到有效的用户信息');
        return;
      }
      
      // 检查是否有Token
      const token = localStorage.getItem('access_token');
      if (!token) {
        console.log('未找到访问令牌');
        return;
      }
      
      console.log('正在请求用户菜单权限，用户ID:', user.id);
      
      // 设置请求头
      const config = {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      };
      
      // 调用后端接口获取用户的菜单权限
      axios.get(`/admin/menus/user/${user.id}`, config)
        .then(response => {
          console.log('菜单权限接口响应:', response);
          // 修复响应数据结构访问（经过拦截器处理后，直接访问code）
          if (response.code === 200) {
            this.userMenus = response.data;
            console.log('用户菜单权限加载成功:', this.userMenus);
          } else if (response.data.code === 200){
            this.userMenus = response.data;
            console.log('用户菜单权限加载成功:', this.userMenus);
          }else {
            this.$message.error(response.message || '获取用户菜单权限失败');
            console.error('获取用户菜单权限失败:', response);
            // 确保在失败时也将userMenus设置为空数组而不是null，避免显示所有菜单
            this.userMenus = [];
          }
        })
        .catch(error => {
          // 使用兼容的方式获取错误信息
          let errorMessage = error.message;
          if (error.response && error.response.data && error.response.data.message) {
            errorMessage = error.response.data.message;
          }
          
          this.$message.error('获取用户菜单权限失败: ' + errorMessage);
          console.error('获取用户菜单权限失败:', error);
          
          // 打印详细的错误信息
          if (error.response) {
            console.error('响应状态:', error.response.status);
            console.error('响应数据:', error.response.data);
            console.error('响应头:', error.response.headers);
          } else if (error.request) {
            console.error('请求信息:', error.request);
          }
        });
    },
    
    // 检查用户是否有指定菜单权限
    hasMenuPermission(menuId) {
      // 管理员拥有所有权限
      if (this.isAdmin) {
        return true;
      }
      
      // 如果权限尚未加载，不显示任何菜单项
      if (this.userMenus === null) {
        return false;
      }
      
      // 如果权限已加载，使用实际权限
      // 确保userMenus是数组且包含指定的menuId
      return Array.isArray(this.userMenus) && this.userMenus.includes(menuId);
    },
    async handleCommand(command) {
      if (command === 'logout') {
        try {
          // 调用后端退出接口
          await logout();
          // 清除用户信息
          localStorage.removeItem('admin_user');
          this.$message.success('退出成功');
          this.$router.push(`/admin/login?redirect=${this.$route.fullPath}`);
        } catch (error) {
          console.error('退出错误:', error);
          // 即使接口错误，也执行本地退出
          localStorage.removeItem('access_token');
          localStorage.removeItem('admin_user');
          localStorage.removeItem('user_role');
          this.$message.success('退出成功');
          this.$router.push('/admin/login');
        }
      } else if (command === 'bigscreen') {
        this.$router.push('/');
      } else if (command === 'profile') {
        this.$router.push('/admin/user-profile');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.admin-aside {
  background-color: #304156;
  height: 100vh;
  overflow-y: auto;

  .logo {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.2);
    
    h3 {
      margin: 0;
      color: #fff;
      font-size: 18px;
      font-weight: 600;
    }
  }
}

.admin-menu {
  border: none;
}

.admin-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.admin-header {
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px !important;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);

  .user-info {
    cursor: pointer;
    color: #333;
    font-size: 14px;
    
    i {
      margin: 0 5px;
    }

    &:hover {
      color: #409EFF;
    }
  }
}

.admin-main {
  padding: 20px;
  overflow-y: auto;
}
</style>